package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/15 20:48
 */
@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
  @Autowired private Configuration configuration;
  @Autowired private FileStorageService fileStorageService;
  @Autowired private ArticleMapper articleMapper;
  @Autowired
  private KafkaTemplate<String,String> kafkaTemplate;

  /**
   * 生成静态文件，并上传到minio
   *
   * @param article
   * @param content
   */
  @Override
  @Async
  public void saveOrUpdate(ApArticle article, String content) {
    try {
      if (StringUtils.isNotBlank(content)) {
        // 1.文章内容通过freemarker生成html文件
        StringWriter out = new StringWriter();
        Template template = configuration.getTemplate("article.ftl");

        Map<String, Object> params = new HashMap<>();
        params.put("content", JSONArray.parseArray(content));

        template.process(params, out);
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());

        // 2.把html文件上传到minio中
        String path = fileStorageService.uploadHtmlFile("", article.getId() + ".html", is);

        // 3.修改ap_article表，保存static_url字段
        article.setStaticUrl(path);
        articleMapper.updateById(article);

        // 封装数据
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(article,vo);
        vo.setLayout(Integer.parseInt(article.getLayout().toString()));
        vo.setContent(content);
        String jsonStr = JSON.toJSONString(vo);
        // 审核成功发送消息给es，新增索引库数据
        kafkaTemplate.send("search_update",jsonStr);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
